import os
import csv
import cv2

training_class_dir = './Final_Training/Images/'
training_roi_img_dir = './Final_Training_ROI/'

for class_dir in os.listdir(training_class_dir):

    # Get the full path
    training_img_dir = training_class_dir + class_dir

    # Get the csv file
    csv_filename = training_img_dir + '/GT-' + class_dir + '.csv'
    with open(csv_filename, 'rb') as f:
        reader = csv.reader(f)

        # Get each image's info
        for row in reader:

            if reader.line_num < 2:
                continue

            img_filename, width, height, x1, y1, x2, y2, label = row[0].split(';')
            
            # Use OpenCV to read the ppm image files
            img = cv2.imread(training_img_dir + '/' +  img_filename)
                        
            # Get the roi
            roi_img = img[int(y1):int(y2), int(x1):int(x2)]

            # Resize the roi image
            roi_img = cv2.resize(roi_img, (64, 64))
            
            if len(label) == 1:
                label = '0' + label
            # Create the new image file name
            new_filename = label + '_' + img_filename.split('.')[0] + '.jpg'

            # Save roi image
            cv2.imwrite(training_roi_img_dir + new_filename, roi_img)
    
    print(class_dir, ' ROI transform finished.')
